﻿using UnityEngine;
using UnityEditor;
using LitJson;
using System.Collections.Generic;
using System.IO;

public class ShowTextureReferencesWindow : EditorWindow
{
    static string directory;
    Vector2 pos;
    List<Data> datas = new List<Data>();
    public void LoadReferences()
    {
        datas.Clear();
        if (Selection.activeGameObject == null)
        {
            return;
        }

        foreach (var child in Selection.activeTransform.TransformChilds())
        {
            var data = new Data();
            data.transform = child;
            data.list = new List<Object>();
            data.replaceList = new List<Object>();
            foreach (var mono in child.GetComponents<MonoBehaviour>())
            {
                var json = EditorJsonUtility.ToJson(mono);
                JsonHelper.Foreach(JsonMapper.ToObject(json)[0].ToJson(), mono.GetType(), (type, key, value) =>
                {
                    if (type == typeof(Texture) || type == typeof(Sprite) || type.IsSubclassOf(typeof(Texture)) || type.IsSubclassOf(typeof(Sprite)))
                    {
                        try
                        {
                            var guid = value["guid"].ToString();
                            var path = AssetDatabase.GUIDToAssetPath(guid);
                            var obj = AssetDatabase.LoadAssetAtPath(path, type);
                            data.list.Add(obj);
                            data.replaceList.Add(null);
                        }
                        catch
                        {

                        }
                    }
                });
            }

            if (data.list.Count == 0)
                continue;
            datas.Add(data);
        }
    }

    private void OnGUI()
    {
        if (datas.Count == 0)
            return;

        pos = EditorGUILayout.BeginScrollView(pos);
        {
            foreach (var item in datas)
            {
                DrawItems(item);
            }
        }
        EditorGUILayout.EndScrollView();
    }

    void DrawItems(Data data)
    {
        var rect = EditorGUILayout.GetControlRect();
        if (GUI.Button(rect, ""))
        {
            Selection.activeObject = data.transform;
        }
        GUI.skin.label.alignment = TextAnchor.MiddleCenter;
        GUI.Label(rect, data.transform.name);
        EditorGUILayout.BeginVertical("Box");
        {
            DrawObject(data.list,data.replaceList);
        }
        EditorGUILayout.EndVertical();
    }

    void DrawObject(List<UnityEngine.Object> list,List<UnityEngine.Object> replaceList)
    {
        for(int i=0;i<list.Count;i++)
        {
            EditorGUILayout.BeginHorizontal();
            {
                var value = list[i];
                EditorGUILayout.ObjectField(value.name, value, value.GetType(), false);

                replaceList[i] = EditorGUILayout.ObjectField("", replaceList[i], value.GetType(), false,GUILayout.MaxWidth(70));
                if(GUILayout.Button("替换", GUILayout.MinHeight(64)))
                {
                    if(replaceList[i]!=null)
                    {
                        UpdateTexture(AssetDatabase.GetAssetPath(replaceList[i]),value);
                        replaceList[i] = null;
                    }
                }
                if (GUILayout.Button("打开文件对话框", GUILayout.MinHeight(64)))
                {
                    var path = EditorUtility.OpenFilePanel("选择替换图片文件", directory, "jpg,png,jpeg,bmp");
                    if (File.Exists(path))
                    {
                        directory = Path.GetDirectoryName(path);
                        UpdateTexture(path, value);
                    }
                }
            }
            EditorGUILayout.EndHorizontal();
        }
    }

    void UpdateTexture(string path, UnityEngine.Object value)
    {
        File.Copy(path, AssetDatabase.GetAssetPath(value), true);
        AssetDatabase.Refresh();
    }

    public struct Data
    {
        public Transform transform;
        public List<UnityEngine.Object> list;
        public List<UnityEngine.Object> replaceList;
    }
}

